class RelativeMemosController < ApplicationController

  helper :sort
  include SortHelper

  before_filter :find_memo, :except => [:new, :create, :index, :search]
  before_filter :find_osp, :only => [:create, :show, :index]
  before_filter :require_login, :only => [:new, :create]

  layout 'base_opensource_p', :except => [:search]

  # GET /open_source_projects
  # GET /open_source_projects.json
  def index
    #
    upgrading = false
    if upgrading
      render :layout => 'base', :template => 'open_source_projects/upgrading'
    else
      @open_source_project.update_column(:view_num_ossean, (@open_source_project.view_num_ossean.to_i+1))
      @open_source_project.save
      @memo = RelativeMemo.new(:open_source_project => @open_source_project)
      @sort_tag = params[:sort_field].to_s

      find_osp_relative_topics(params[:sort_field].to_s)

      respond_to do |format|
        format.html {
          render :layout => "base_opensource_p"
        }
        format.json { render json: @open_source_project }
      end
    end
  end

  # GET /open_source_projects/1
  # GET /open_source_projects/1.json
  REPLIES_PER_PAGE = 10 unless const_defined?(:REPLIES_PER_PAGE)

  def show
    pre_count = REPLIES_PER_PAGE

    @project_info=@open_source_project.open_source_project_infos.first
    # @memo = @memo.root # 取出楼主，防止输入帖子id让回复作为主贴显示
    @topic.update_column(:view_count_trustie, (@topic.view_count_trustie.to_i + 1))

    page = params[:page]
    if params[:r] && page.nil?
      offset = @topic.children.where("#{RelativeMemo.table_name}.id < ?", params[:r].to_i).count
      page = 1 + offset / pre_count
    else

    end
    #@replies=@topic.child.all

    #gcm
    @replies=@topic.children.
        includes(:author).
        reorder("#{RelativeMemo.table_name}.created_time ASC")
    @reply_count = @replies.count
    @reply_pages = Paginator.new @reply_count, pre_count, page
    @replies = @replies.
        limit(@reply_pages.per_page).
        offset(@reply_pages.offset)
    #gcm end

    @memo_new = RelativeMemo.new


    # @memo = Memo.find_by_id(params[:id])
    # @forum = Forum.find(params[:forum_id])
    # @replies = @memo.replies
    # @mome_new = Memo.new

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @memo }
    end
  end


  # GET /open_source_projects/new
  # GET /open_source_projects/new.json
  def new
    @open_source_project = OpenSourceProject.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @open_source_project }
    end
  end

  # GET /open_source_projects/1/edit
  def edit
    @open_source_project = OpenSourceProject.find(params[:id])
  end

  # POST /open_source_projects
  # POST /open_source_projects.json
  def create
    @memo = RelativeMemo.new(params[:relative_memo])
    # @memo.url = "http://forge.trustie.net/open_source_projects"
    @memo.osp_id = params[:open_source_project_id]
    @memo.author_id = User.current.id
    @memo.crawled_time=Time.now

    respond_to do |format|
      if @memo.save
        RelativeMemoToOpenSourceProject.set_table_name RelativeMemoToOpenSourceProject.getTableName params[:open_source_project_id]
        RelativeMemoToOpenSourceProject.create(:osp_id => params[:open_source_project_id],
                                               :relative_memo_id => @memo.id)
        format.html { redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}" }
        format.json { render json: @memo, status: :created, location: @memo }
      else
        flash[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}"
        # back_error_page = @memo.parent_id.nil? ? forum_path(@forum) : forum_memo_path(@forum, @memo.parent_id)
        format.html { redirect_to back_memo_url } #, error: "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}" }
        format.json { render json: @memo.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /open_source_projects/1
  # PUT /open_source_projects/1.json
  def update
    @open_source_project = OpenSourceProject.find(params[:id])

    respond_to do |format|
      if @open_source_project.update_attributes(params[:open_source_project])
        format.html { redirect_to @open_source_project, notice: 'Open source project was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @open_source_project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /open_source_projects/1
  # DELETE /open_source_projects/1.json
  def destroy
    @open_source_project = OpenSourceProject.find(params[:id])
    @open_source_project.destroy

    respond_to do |format|
      format.html { redirect_to open_source_projects_url }
      format.json { head :no_content }
    end
  end

  def search
    #year=2013
    if "".eql?(params[:name]) || params[:name].nil?
      params[:name] = " "
    end

    #请求服务
    require 'net/http'
    require 'json'
    require 'logger'
    logger = Logger.new(STDOUT)  #输出到控制台
    per_page_option=10
    @sort_tag = params[:sort_field].to_s
    @name = params[:name].downcase

    #access java webservice by zyr
    oldverb = $VERBOSE; $VERBOSE = nil
    require 'iconv'
    $VERBOSE = oldverb

    require 'rubygems'
    require 'soap/wsdlDriver'

    a_URL = "http://localhost:8083/testWebService_war/services/memoquery?wsdl"
    soap_client = SOAP::WSDLDriverFactory.new(a_URL).create_rpc_driver

    result = soap_client.query(@name)
    #memo_ids = [58,79,98,2207482,2207571,2207591,2207657,2207710,2208867,2209348,2209667,2209694,2210046]
    #logger.info(result)
    return_memos = []#

    result.each do |id|
      id = id.to_i
      memo = RelativeMemo.find_by_id(id)
      return_memos << memo
    end

    @topics_count = return_memos.length.to_i
    @topics_pages = Paginator.new @topics_count, per_page_option, params[:page]
    current_page = @topics_pages.page
    @topics = return_memos[(current_page-1)*per_page_option,per_page_option]

    respond_to do |format|
      format.html { render :layout => "base"
      }
    end


  end

  #
    # memo_ids = [58,79,98,2207482,2207571,2207591,2207657,2207710,2208867,2209348,2209667,2209694,2210046]
    # relative_memos = []
    # # 查询出id对应的项目
    # memo_ids.each do |id|
    #   id = id.to_i
    #   memo = RelativeMemo.find_by_id(id)
    #   logger.info(memo.title)
    #
    #   relative_memos << memo
    # end
    #search = RelativeMemo.search do
    #   fulltext params[:name].downcase do
    #     fields(:title)
    #     fields(:tags)
    #     boost_fields :title => 3.0
    #     boost_fields :tags => 2.0
    #     #phrase_fields :title => 2.0
    #   end
    #   if "review_num DESC".eql?(params[:sort_field].to_s)
    #     order_by(:review_num, :desc)
    #   elsif "review_num ASC".eql?(params[:sort_field].to_s)
    #     order_by(:review_num, :asc)
    #   elsif "created_time DESC".eql?(params[:sort_field].to_s)
    #     order_by(:created_time, :desc)
    #   elsif "created_time ASC".eql?(params[:sort_field].to_s)
    #     order_by(:created_time, :asc)
    #   end
        
      #order_by(:created_time, :desc)
      #with(:created_time, Date.new(year,01,01)..Date.new(year+1,01,01))
      # any_of do
        # # with :parent_id, 0
        # # with :parent_id, nil
        # with :source, params[:name].downcase
      # end
      #paginate :page => params[:page], :per_page => per_page_option
    #end
    #@topics = search.results

  private

  def find_memo
    return unless find_osp
    @topic = @open_source_project.topics.find(RelativeMemo.find(params[:id]).root.id)
  rescue ActiveRecord::RecordNotFound
    render_404
    nil
  end

  def find_osp
    @open_source_project = OpenSourceProject.find(params[:open_source_project_id])
  rescue ActiveRecord::RecordNotFound
    render_404
    nil
  end

  def back_memo_url
    open_source_project_relative_memo_path(@open_source_project, (@memo ))
  end

  # find relative_topics of osp order by
  def find_osp_relative_topics(sort_by)
    #approach 1
    per_page_option = 10

    @topics_count = @open_source_project.relative_topics.count #@topics.count
    @topics_pages = Paginator.new @topics_count, per_page_option, params['page']
    RelativeMemoToOpenSourceProject.set_table_name RelativeMemoToOpenSourceProject.getTableName @open_source_project.id
    @relative_memo_ids=RelativeMemoToOpenSourceProject.where(osp_id: @open_source_project.id).order(sort_by).offset(@topics_pages.offset).limit(@topics_pages.per_page)
    #@relative_topics=RelativeMemo.where(id: @relative_memo_ids).order('created_time DESC')
    #@tech_trend_topics=@relative_topics.order('created_time DESC').limit(7)
=begin
    #approach 2
    @relative_topics= @open_source_project.topics.order('relative_memos.review_num DESC, relative_memos.created_time DESC').limit(10)
    @tech_trend_topics=@relative_topics.reorder('relative_memos.created_time DESC').first(7)
=end
  end

end
